using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using LS.Digitize;
using LS.Editor;
using LS.GameKit.Digitize;

namespace LS.GameKit.Editor
{
    public class AssetReferenceSetupMenu
    {
        [MenuItem("Assets/Lancer Studio/Add To References Config")]
        public static void ReferencesAssets()
        {
            var configs = LSPathEditor.FindAssetsFromProject<AssetReferencesConfigScriptableObject>();
            if (configs.Length == 0)
            {
                Debug.LogError($"Can not found AssetReferencesConfigScriptableObject. Use menu Assets -> Create -> Lancer Studio -> Asset References Config to create config file.");
                return;
            }

            
            var objs = Selection.objects;
            List<AssetInfo> m_infos = objs.Select(o =>
            {
                string path = AssetDatabase.GetAssetPath(o);
                string guid = AssetDatabase.AssetPathToGUID(path);
                return new AssetInfo(path, guid);
            }).ToList();
            for (int i = 0; i < configs.Length; i++)
            {
                var config = configs[i];
                bool added = false;
                for (int j = 0; j < m_infos.Count; j++)
                {
                    if (!config.assetReference.ContainsGuid(m_infos[j].Guid))
                    {
                        config.assetReference.RegisterAsset(m_infos[j]);
                        added = true;
                    }
                }
                
                if(added)
                {
                    EditorUtility.SetDirty(config);
                    AssetDatabase.SaveAssetIfDirty(config);
                }
            }
        }
        
        [MenuItem("Assets/Lancer Studio/Add To References Config", true)]
        public static bool ReferencesAssetsValidate()
        {
            return Selection.objects.Length > 0;
        }
    }
}
